<template>
    <div class="personal-center">
        <div class="container">
            <div class="left">
                <ul>
                    <li class="item active">
                        <svg class="icon" aria-hidden="true">
                            <use xlink:href="#icon-yonghu"></use>
                        </svg>
                        <span>个人资料</span>
                    </li>
                </ul>
            </div>
            <div class="right">
                <div class="profile-card">
                    <h2>个人资料</h2>
                    <div class="profile-form">
                        <!-- 头像上传 -->
                        <div class="form-group avatar-upload">
                            <label>头像</label>
                            <div class="avatar-preview">
                                <img :src="userInfo.avatar_url" alt="头像" class="avatar-img">
                                <input type="file" ref="avatarInput" @change="handleAvatarChange" accept="image/*"
                                    style="display: none;">
                                <button @click="triggerAvatarUpload" class="upload-btn">更换头像</button>
                            </div>
                        </div>

                        <!-- 用户名修改 -->
                        <div class="form-group">
                            <label for="username">用户名</label>
                            <input type="text" id="username" v-model="userInfo.name">
                            <button @click="updateUsername" class="save-btn">保存</button>
                        </div>

                        <!-- 密码修改 -->
                        <div class="form-group">
                            <label for="currentPassword">当前密码</label>
                            <input type="text" id="currentPassword" v-model="passwordForm.currentPassword">

                            <label for="newPassword">新密码</label>
                            <input type="text" id="newPassword" v-model="passwordForm.newPassword">

                            <label for="confirmPassword">确认新密码</label>
                            <input type="text" id="confirmPassword" v-model="passwordForm.confirmPassword">

                            <button @click="updatePassword" class="save-btn">修改密码</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance } from 'vue';
import { useStore } from 'vuex';
import api from '../../../api/index';
import { ElMessage } from 'element-plus';
import { emitter } from '@/utils/eventBus';


const store = useStore();

// 用户信息
const userInfo = ref({
    name: '',
    avatar_url: ''
});

// 密码表单
const passwordForm = ref({
    currentPassword: '',
    newPassword: '',
    confirmPassword: ''
});

// 头像上传input引用
const avatarInput = ref(null);

// 获取用户信息
const fetchUserInfo = async () => {
    const res = await api.getUserInfo({ userid: store.state.userid });
    if (res.code === 200) {
        userInfo.value = res.data[0];
    }
};

// 触发头像上传
const triggerAvatarUpload = () => {
    avatarInput.value.click();
};

// 处理头像变更
const handleAvatarChange = async (e) => {
    const file = e.target.files[0];
    if (!file) return;

    // 创建FormData对象
    const formData = new FormData();
    formData.append('avatar', file);
    formData.append('userid', store.state.userid);


    try {
        const res = await api.uploadAvatar(formData);
        console.log(res)
        if (res.code === 200) {
            // 更新本地头像显示
            userInfo.value.avatar_url = res.data.avatar_url;
            // 可以在这里触发全局状态更新，如果需要的话
            ElMessage.success('头像上传成功');
            // 保存成功后刷新Header组件
            emitter.emit('refresh-user-info');
        }
    } catch (error) {
        console.error('上传头像失败:', error);
    }
};

// 更新用户名
const updateUsername = async () => {
    if (!userInfo.value.name.trim()) {
        alert('用户名不能为空');
        return;
    }

    try {
        const res = await api.updateUsername({
            userid: store.state.userid,
            name: userInfo.value.name
        });

        if (res.code === 200) {
            ElMessage.success('用户名更新成功');
            // 刷新
            fetchUserInfo();
            // 保存成功后刷新Header组件
            emitter.emit('refresh-user-info');
        } else {
            ElMessage.error(res.message || '用户名更新失败');
        }
    } catch (error) {
        console.error('更新用户名失败:', error);
        ElMessage.error('更新用户名失败');
    }
};

// 更新密码
const updatePassword = async () => {
    const { currentPassword, newPassword, confirmPassword } = passwordForm.value;

    if (!currentPassword || !newPassword || !confirmPassword) {
        ElMessage.error('密码不能为空');
        return;
    }

    if (newPassword !== confirmPassword) {
        ElMessage.error('两次输入的密码不一致');
        return;
    }

    if (newPassword.length < 6) {
        ElMessage.error('密码长度不能少于6位');
        return;
    }

    try {
        const res = await api.updatePassword({
            userid: store.state.userid,
            currentPassword,
            newPassword
        });

        if (res.code === 200) {
            ElMessage.success('密码修改成功');
            // 清空密码表单
            passwordForm.value = {
                currentPassword: '',
                newPassword: '',
                confirmPassword: ''
            };
            // 保存成功后刷新Header组件
            emitter.emit('refresh-user-info');
        } else {
            ElMessage.error(res.message || '密码修改失败');
        }
    } catch (error) {
        console.error('修改密码失败:', error);
        ElMessage.error(res.message || '密码修改失败');
    }
};

onMounted(() => {
    fetchUserInfo();
});
</script>

<style lang="less" scoped>
.personal-center {
    margin-top: 20px;

    .container {
        width: 1100px;
        margin: 0 auto;
        display: flex;

        .left {
            width: 200px;

            .item {
                width: 80%;
                height: 40px;
                background-color: #f6f6f6;
                display: flex;
                align-items: center;
                margin-bottom: 10px;
                cursor: pointer;

                &.active {
                    background-color: #e5e5e5;
                }

                .icon {
                    margin: 0 10px;
                }

                span {
                    font-weight: bold;
                }
            }
        }

        .right {
            width: 600px;
            margin-left: 40px;

            .profile-card {
                background-color: white;
                padding: 20px;
                border-radius: 5px;
                box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);

                h2 {
                    font-size: 20px;
                    margin-bottom: 20px;
                    padding-bottom: 10px;
                    border-bottom: 1px solid #eee;
                }

                .profile-form {
                    .form-group {
                        margin-bottom: 20px;

                        label {
                            display: block;
                            margin-bottom: 5px;
                            font-weight: bold;
                        }

                        input[type="text"],
                        input[type="password"] {
                            width: 100%;
                            padding: 8px;
                            border: 1px solid #ddd;
                            border-radius: 4px;
                            margin-bottom: 10px;
                        }

                        .save-btn {
                            background-color: #4CAF50;
                            color: white;
                            border: none;
                            padding: 8px 15px;
                            border-radius: 4px;
                            cursor: pointer;
                            transition: background-color 0.3s;

                            &:hover {
                                background-color: #45a049;
                            }
                        }
                    }

                    .avatar-upload {
                        .avatar-preview {
                            display: flex;
                            align-items: center;
                            margin-bottom: 15px;

                            .avatar-img {
                                width: 80px;
                                height: 80px;
                                border-radius: 50%;
                                object-fit: cover;
                                margin-left: 15px;
                                margin-right: 15px;
                                border: 1px solid #ddd;
                            }

                            .upload-btn {
                                background-color: #2196F3;
                                color: white;
                                border: none;
                                padding: 8px 15px;
                                border-radius: 4px;
                                cursor: pointer;
                                transition: background-color 0.3s;

                                &:hover {
                                    background-color: #0b7dda;
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
</style>